const config = require('../config');
const sha1 = require('sha1');
const { getXmlData, getXMlJson, formatWxJson } = require('../util/util');
const replyMsg = require('./replyMsg');
const template = require('./template');

module.exports = () => {
    /**处理消息回复 */
    return async (req, res, next) => {

        const { echostr, nonce, timestamp, signature } = req.query;
        const { token } = config;
        //将数组拼成字符串
        const arrstr = [timestamp, nonce, token].sort().join('');
        if (req.method === 'GET') {
            if (signature === sha1(arrstr)) {
                res.send(echostr);
            } else {
                res.end('error');
            }
        } else if (req.method === 'POST') {
            if (signature !== sha1(arrstr)) {
                res.end('error');
            }
            const content = await getXmlData(req);
            if (content) {
                const tt = await getXMlJson(content);
                const message = formatWxJson(tt.xml);
                if (!message.Event) { //消息类型
                    const options = replyMsg(message);
                    const data = template(options);
                    if (typeof (data) !== 'undefined') {
                        res.send(data);
                    }
                } else { //事件类型

                }
            } else {
                req.end('error');
            }
        }


    }
}